package com.ruoyi.system.controller;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.system.domain.SysMember;
import com.ruoyi.system.domain.dto.SmsRegisterDto;
import com.ruoyi.system.mapper.SysMemberMapper;
import com.ruoyi.system.service.ISysUserService;
//import com.ruoyi.system.service.impl.AliyunSmsService;
import com.ruoyi.system.service.impl.SmsService;
import com.ruoyi.system.service.impl.SysMemberServiceImpl;
import com.ruoyi.system.util.SmsCodeUtil;
//import com.ruoyi.system.util.SmsUtil;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@Anonymous
@RequestMapping("/api/smsTwo")
public class SmsRegisterControllerTwo extends BaseController {

//    @Autowired
//    private AliyunSmsService smsService;

    @Autowired
    private SmsCodeUtil smsCodeUtil;

    @Autowired
    private ISysUserService userService;
    @Autowired
    private SmsService smsService;
//    @Autowired
//    private SmsUtil smsUtil;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private SysMemberServiceImpl sysMemberServiceImpl;
    @Autowired
    private SysMemberMapper sysMemberMapper;
//    @Autowired
//    private TokenService tokenService;

    /**
     * 发送注册验证码
     */
    @GetMapping("/sendRegisterCode/{phoneNumber}")
    public AjaxResult sendRegisterCode(@PathVariable String phoneNumber) {

        if (ObjectUtils.isNotEmpty(redisCache.getCacheObject("sms_code:" + phoneNumber))){
            return AjaxResult.error("请在一分钟后重试～");
        }

        if (sysMemberServiceImpl.checkPhoneByPhone(phoneNumber)) {
            return AjaxResult.error("该手机号已注册！");
        }

        // 生成并发送验证码
        String code = smsCodeUtil.generateCode();
        // 假设短信模板需要一个验证码参数
        String templateParam = "{\"code\":\"" + code + "\"}";

        boolean isSuccess = smsService.sendSms(phoneNumber, templateParam);
        if (isSuccess) {
            smsCodeUtil.saveCode(phoneNumber, code);
            return AjaxResult.success("短信发送成功");
        } else {
            return AjaxResult.error("短信发送失败");
        }

    }

    /**
     * 手机号注册
     */
    @PostMapping("/register")
    public AjaxResult register(@RequestBody SmsRegisterDto registerDto) {
        // 验证验证码
        if (!smsCodeUtil.verifyCode(registerDto.getPhoneNumber(), registerDto.getCode())) {
            return AjaxResult.error("验证码错误或已过期");
        }

        SysMember param = new SysMember();
        param.setPhonenumber(registerDto.getPhoneNumber());
        List<SysMember> sysMembers = sysMemberMapper.selectSysMemberList(param);

        if (!sysMembers.isEmpty()) {
            SysMember sysMember = sysMembers.get(0);
            // 模拟登录用户，实际项目中应从数据库获取
            LoginUser loginUser = new LoginUser();
            loginUser.setUser(new SysUser(1L));

            // 生成与登录相同的Token
//            String token = tokenService.createToken(loginUser);
        }else{
            // 注册用户
            SysUser user = new SysUser();
            user.setPhonenumber(registerDto.getPhoneNumber());
            user.setUserName(registerDto.getPhoneNumber());
            user.setUserType("1");
            user.setNickName("用户_" + registerDto.getPhoneNumber().substring(7));
            user.setPassword(SecurityUtils.encryptPassword(registerDto.getPassword()));
            boolean regFlag = userService.registerUser(user);
            if (!regFlag)
            {
                return AjaxResult.error("注册失败,请联系系统管理人员");
            }
            return AjaxResult.error("注册成功");
        }


        AjaxResult ajax = AjaxResult.success();
        // 生成令牌

     return ajax;
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId)
    {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr());
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }


}